package com.engine.salary.service.impl;

import com.alibaba.fastjson.JSON;
import com.api.formmode.mybatis.util.SqlProxyHandle;
import com.engine.common.util.ServiceUtil;
import com.engine.core.impl.Service;
import com.engine.hrmelog.entity.dto.LoggerContext;
import com.engine.salary.config.SalaryElogConfig;
import com.engine.salary.constant.SalaryDefaultTenantConstant;
import com.engine.salary.encrypt.EncryptUtil;
import com.engine.salary.entity.datacollection.DataCollectionEmployee;
import com.engine.salary.entity.siaccount.param.BalanceAccountBaseParam;
import com.engine.salary.entity.siaccount.param.InspectAccountParam;
import com.engine.salary.entity.siaccount.po.InsuranceAccountBatchPO;
import com.engine.salary.entity.siaccount.po.InsuranceAccountDetailPO;
import com.engine.salary.entity.siarchives.po.*;
import com.engine.salary.entity.sicategory.po.ICategoryPO;
import com.engine.salary.entity.sischeme.po.InsuranceSchemeDetailPO;
import com.engine.salary.entity.taxagent.po.TaxAgentPO;
import com.engine.salary.enums.OperateTypeEnum;
import com.engine.salary.enums.siaccount.BillStatusEnum;
import com.engine.salary.enums.siaccount.PaymentStatusEnum;
import com.engine.salary.enums.siaccount.ResourceFromEnum;
import com.engine.salary.enums.sicategory.DeleteTypeEnum;
import com.engine.salary.enums.sicategory.IsPaymentEnum;
import com.engine.salary.enums.sicategory.PaymentScopeEnum;
import com.engine.salary.exception.SalaryRunTimeException;
import com.engine.salary.mapper.siaccount.InsuranceAccountBatchMapper;
import com.engine.salary.mapper.siaccount.InsuranceAccountDetailMapper;
import com.engine.salary.mapper.siarchives.FundSchemeMapper;
import com.engine.salary.mapper.siarchives.InsuranceBaseInfoMapper;
import com.engine.salary.mapper.siarchives.OtherSchemeMapper;
import com.engine.salary.mapper.siarchives.SocialSchemeMapper;
import com.engine.salary.mapper.sicategory.ICategoryMapper;
import com.engine.salary.mapper.sischeme.InsuranceSchemeDetailMapper;
import com.engine.salary.mapper.taxagent.TaxAgentMapper;
import com.engine.salary.service.SIAccountService;
import com.engine.salary.service.SIBalanceService;
import com.engine.salary.service.SalaryEmployeeService;
import com.engine.salary.util.SalaryEntityUtil;
import com.engine.salary.util.SalaryI18nUtil;
import com.engine.salary.util.db.IdGenerator;
import com.engine.salary.util.db.MapperProxyFactory;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import weaver.hrm.User;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @Author: sy
 * @Description: 福利台账-补差实现类
 * @Date: 2022/12/8
 **/
public class SIBalanceServiceImpl extends Service implements SIBalanceService {

    private InsuranceAccountDetailMapper getInsuranceAccountDetailMapper() {
        return SqlProxyHandle.getProxy(InsuranceAccountDetailMapper.class);
    }

    private SIAccountService getSIAccountService(User user) {
        return ServiceUtil.getService(SIAccountServiceImpl.class, user);
    }

    private SocialSchemeMapper getSocialSchemeMapper() {
        return MapperProxyFactory.getProxy(SocialSchemeMapper.class);
    }

    private FundSchemeMapper getFundSchemeMapper() {
        return MapperProxyFactory.getProxy(FundSchemeMapper.class);
    }

    private OtherSchemeMapper getOtherSchemeMapper() {
        return MapperProxyFactory.getProxy(OtherSchemeMapper.class);
    }

    private ICategoryMapper getICategoryMapper() {
        return MapperProxyFactory.getProxy(ICategoryMapper.class);
    }

    private InsuranceSchemeDetailMapper getInsuranceSchemeDetailMapper() {
        return MapperProxyFactory.getProxy(InsuranceSchemeDetailMapper.class);
    }

    private InsuranceBaseInfoMapper getInsuranceBaseInfoMapper() {
        return MapperProxyFactory.getProxy(InsuranceBaseInfoMapper.class);
    }

    private EncryptUtil encryptUtil = new EncryptUtil();

    private InsuranceAccountBatchMapper getInsuranceAccountBatchMapper() {
        return MapperProxyFactory.getProxy(InsuranceAccountBatchMapper.class);
    }

    private TaxAgentMapper getTaxAgentMapper() {
        return MapperProxyFactory.getProxy(TaxAgentMapper.class);
    }

    private SalaryEmployeeService getSalaryEmployeeService(User user) {
        return ServiceUtil.getService(SalaryEmployeeServiceImpl.class, user);
    }

    @Override
    public void del(InspectAccountParam param, Long employeeId) {

        //入参判断
        if (CollectionUtils.isEmpty(param.getIds()) || param.getPaymentOrganization() == null || param.getBillMonth() == null) {
            throw new SalaryRunTimeException(SalaryI18nUtil.getI18nLabel(84026, "参数错误"));
        }

        //根据id删除
        List<List<Long>> partition = Lists.partition((List<Long>) param.getIds(), 100);
        partition.forEach(getInsuranceAccountDetailMapper()::batchDelAccountDetailsByIds);
        //记录操作日志
        LoggerContext<InsuranceAccountDetailPO> loggerContext = new LoggerContext();
        loggerContext.setUser(user);
        loggerContext.setTargetId(param.getIds().stream().map(String::valueOf).collect(Collectors.joining(",")));
        loggerContext.setTargetName(param.getIds().stream().map(String::valueOf).collect(Collectors.joining(",")));
        loggerContext.setOperateType(OperateTypeEnum.DELETE.getValue());
        loggerContext.setOperateTypeName(SalaryI18nUtil.getI18nLabel(0, "福利台账明细表-删除补差核算记录"));
        loggerContext.setOperatedesc(SalaryI18nUtil.getI18nLabel(0, "福利台账明细表-删除补差核算记录"));
        SalaryElogConfig.siAccountLoggerTemplate.write(loggerContext);
        //刷新bill_batch表中统计信息
        getSIAccountService(user).refreshBillBatch(param.getPaymentOrganization(), param.getBillMonth());
    }

    /**
     * 获取待编辑的补差费用相关福利项
     */
    @Override
    public List<Map<String, String>> getPaymentGroup(BalanceAccountBaseParam param) {

        Long paymentOrganization = param.getPaymentOrganization();
        Long employeeId = param.getEmployeeId();
        InsuranceArchivesSocialSchemePO socialSchemePO = new InsuranceArchivesSocialSchemePO();
        InsuranceArchivesFundSchemePO fundSchemePO = new InsuranceArchivesFundSchemePO();
        InsuranceArchivesOtherSchemePO otherSchemePO = new InsuranceArchivesOtherSchemePO();

        List<InsuranceArchivesSocialSchemePO> socialSchemePOList = getSocialSchemeMapper().getSocialByEmployeeIdAndPayOrg(InsuranceArchivesEmployeePO.builder()
                .employeeId(employeeId)
                .paymentOrganization(paymentOrganization)
                .build());
        if (socialSchemePOList.size() > 0) {
            encryptUtil.decryptList(socialSchemePOList, InsuranceArchivesSocialSchemePO.class);
            socialSchemePO = socialSchemePOList.get(0);
        }

        List<InsuranceArchivesFundSchemePO> fundSchemePOList = getFundSchemeMapper().getFundByEmployeeIdAndPayOrg(InsuranceArchivesEmployeePO.builder()
                .employeeId(employeeId)
                .paymentOrganization(paymentOrganization)
                .build());
        if (fundSchemePOList.size() > 0) {
            encryptUtil.decryptList(fundSchemePOList, InsuranceArchivesFundSchemePO.class);
            fundSchemePO = fundSchemePOList.get(0);
        }

        List<InsuranceArchivesOtherSchemePO> otherSchemePOList = getOtherSchemeMapper().getOtherByEmployeeIdAndPayOrg(InsuranceArchivesEmployeePO.builder()
                .employeeId(employeeId)
                .paymentOrganization(paymentOrganization)
                .build());
        if (otherSchemePOList.size() > 0) {
            encryptUtil.decryptList(otherSchemePOList, InsuranceArchivesOtherSchemePO.class);
            otherSchemePO = otherSchemePOList.get(0);
        }

        List<ICategoryPO> allCategoryList = getICategoryMapper().listAll();
        Map<Long, String> categoryNameMap = SalaryEntityUtil.convert2Map(allCategoryList, ICategoryPO::getId, ICategoryPO::getInsuranceName);
        Map<Long, Integer> welfareTypeMap = SalaryEntityUtil.convert2Map(allCategoryList, ICategoryPO::getId, ICategoryPO::getWelfareType);

        List<Map<String, String>> resultList = new ArrayList<>();

        if (socialSchemePO != null && (StringUtils.isNotBlank(socialSchemePO.getSocialPaymentBaseString()) || StringUtils.isNotBlank(socialSchemePO.getSocialPaymentComBaseString()) )) {
            Map<String, String> socialMap = JSON.parseObject(socialSchemePO.getSocialPaymentBaseString(), new HashMap<String, String>().getClass());
            Map<String, String> socialComMap = JSON.parseObject(socialSchemePO.getSocialPaymentComBaseString(), new HashMap<String, String>().getClass());
            List<String> socialIds = new ArrayList<>();
            socialIds.addAll(socialMap.keySet());
            if (socialComMap != null) {
                socialIds.addAll(socialComMap.keySet());
            }
            socialIds = socialIds.stream().distinct().collect(Collectors.toList());
            //查询该福利方案下开启缴纳的福利项
            List<String> insuranceIdAndScopeList = payInsuranceIdAndScopeList(socialSchemePO.getSocialSchemeId());
            List<InsuranceSchemeDetailPO> insuranceSchemeDetailPOS = getInsuranceSchemeDetailMapper().listBySchemeIds(Collections.singletonList(socialSchemePO.getSocialSchemeId()));
            Map<String, Integer> schemeValidNumMap = SalaryEntityUtil.convert2Map(insuranceSchemeDetailPOS, po -> po.getInsuranceId() + "-" + po.getPaymentScope(), InsuranceSchemeDetailPO::getValidNum);
            socialIds.forEach(k -> {
                String welfareTypeName =  welfareTypeMap.get(Long.valueOf(k)) == 1 ? "社保" : (welfareTypeMap.get(Long.valueOf(k)) == 2 ? "公积金" : "企业年金及其它福利" );
                String welfareTypeSign =  welfareTypeMap.get(Long.valueOf(k)) == 1 ? "social" : (welfareTypeMap.get(Long.valueOf(k)) == 2 ? "fund" : "other" );
                if (insuranceIdAndScopeList.contains(k + "-" + PaymentScopeEnum.SCOPE_COMPANY.getValue())) {
                    Map<String, String> comMap = new HashMap<>();
//                    comMap.put("title", welfareTypeName + "公司" + "缴纳");
                    comMap.put("title", welfareTypeName);
                    comMap.put("titleSign", welfareTypeSign);
                    comMap.put("insuranceId", k);
                    comMap.put("insuranceName", categoryNameMap.get(Long.valueOf(k)));
                    comMap.put("paymentScope", "公司");
                    comMap.put("paymentScopeSign", "com");
                    comMap.put("validNum",schemeValidNumMap.getOrDefault(k + "-" + PaymentScopeEnum.SCOPE_COMPANY.getValue(), 2).toString());
                    resultList.add(comMap);
                }
                if (insuranceIdAndScopeList.contains(k + "-" + PaymentScopeEnum.SCOPE_PERSON.getValue())) {
                    Map<String, String> perMap = new HashMap<>();
//                    perMap.put("title", welfareTypeName + "个人" + "缴纳");
                    perMap.put("title", welfareTypeName);
                    perMap.put("titleSign", welfareTypeSign);
                    perMap.put("insuranceId", k);
                    perMap.put("insuranceName", categoryNameMap.get(Long.valueOf(k)));
                    perMap.put("paymentScope", "个人");
                    perMap.put("paymentScopeSign", "per");
                    perMap.put("validNum",schemeValidNumMap.getOrDefault(k + "-" + PaymentScopeEnum.SCOPE_PERSON.getValue(), 2).toString());
                    resultList.add(perMap);
                }
            });

        }
        if (fundSchemePO != null && (StringUtils.isNotBlank(fundSchemePO.getFundPaymentBaseString()) || StringUtils.isNotBlank(fundSchemePO.getFundPaymentComBaseString()))) {
            Map<String, String> fundMap = JSON.parseObject(fundSchemePO.getFundPaymentBaseString(), new HashMap<String, String>().getClass());
            Map<String, String> fundComMap = JSON.parseObject(fundSchemePO.getFundPaymentComBaseString(), new HashMap<String, String>().getClass());
            List<String> fundIds = new ArrayList<>();
            fundIds.addAll(fundMap.keySet());
            if (fundComMap != null) {
                fundIds.addAll(fundComMap.keySet());
            }
            fundIds = fundIds.stream().distinct().collect(Collectors.toList());
            //查询该福利方案下开启缴纳的福利项
            List<String> insuranceIdAndScopeList = payInsuranceIdAndScopeList(fundSchemePO.getFundSchemeId());
            List<InsuranceSchemeDetailPO> insuranceSchemeDetailPOS = getInsuranceSchemeDetailMapper().listBySchemeIds(Collections.singletonList(fundSchemePO.getFundSchemeId()));
            Map<String, Integer> schemeValidNumMap = SalaryEntityUtil.convert2Map(insuranceSchemeDetailPOS, po -> po.getInsuranceId() + "-" + po.getPaymentScope(), InsuranceSchemeDetailPO::getValidNum);
            fundIds.forEach(k -> {
                String welfareTypeName =  welfareTypeMap.get(Long.valueOf(k)) == 1 ? "社保" : (welfareTypeMap.get(Long.valueOf(k)) == 2 ? "公积金" : "企业年金及其它福利" );
                String welfareTypeSign =  welfareTypeMap.get(Long.valueOf(k)) == 1 ? "social" : (welfareTypeMap.get(Long.valueOf(k)) == 2 ? "fund" : "other" );
                if (insuranceIdAndScopeList.contains(k + "-" + PaymentScopeEnum.SCOPE_COMPANY.getValue())) {
                    Map<String, String> comMap = new HashMap<>();
//                    comMap.put("title", welfareTypeName + "公司" + "缴纳");
                    comMap.put("title", welfareTypeName);
                    comMap.put("titleSign", welfareTypeSign);
                    comMap.put("insuranceId", k);
                    comMap.put("insuranceName", categoryNameMap.get(Long.valueOf(k)));
                    comMap.put("paymentScope", "公司");
                    comMap.put("paymentScopeSign", "com");
                    comMap.put("validNum",schemeValidNumMap.getOrDefault(k + "-" + PaymentScopeEnum.SCOPE_COMPANY.getValue(), 2).toString());
                    resultList.add(comMap);
                }
                if (insuranceIdAndScopeList.contains(k + "-" + PaymentScopeEnum.SCOPE_PERSON.getValue())) {
                    Map<String, String> perMap = new HashMap<>();
//                    perMap.put("title", welfareTypeName + "个人" + "缴纳");
                    perMap.put("title", welfareTypeName);
                    perMap.put("titleSign", welfareTypeSign);
                    perMap.put("insuranceId", k);
                    perMap.put("insuranceName", categoryNameMap.get(Long.valueOf(k)));
                    perMap.put("paymentScope", "个人");
                    perMap.put("paymentScopeSign", "per");
                    perMap.put("validNum",schemeValidNumMap.getOrDefault(k + "-" + PaymentScopeEnum.SCOPE_PERSON.getValue(), 2).toString());
                    resultList.add(perMap);
                }
            });

        }
        if (otherSchemePO != null && (StringUtils.isNotBlank(otherSchemePO.getOtherPaymentBaseString()) || StringUtils.isNotBlank(otherSchemePO.getOtherPaymentComBaseString()))) {
            Map<String, String> otherMap = JSON.parseObject(otherSchemePO.getOtherPaymentBaseString(), new HashMap<String, String>().getClass());
            Map<String, String> otherComMap = JSON.parseObject(otherSchemePO.getOtherPaymentComBaseString(), new HashMap<String, String>().getClass());
            List<String> otherIds = new ArrayList<>();
            otherIds.addAll(otherMap.keySet());
            if (otherComMap != null) {
                otherIds.addAll(otherComMap.keySet());
            }
            otherIds = otherIds.stream().distinct().collect(Collectors.toList());
            //查询该福利方案下开启缴纳的福利项
            List<String> insuranceIdAndScopeList = payInsuranceIdAndScopeList(otherSchemePO.getOtherSchemeId());
            List<InsuranceSchemeDetailPO> insuranceSchemeDetailPOS = getInsuranceSchemeDetailMapper().listBySchemeIds(Collections.singletonList(otherSchemePO.getOtherSchemeId()));
            Map<String, Integer> schemeValidNumMap = SalaryEntityUtil.convert2Map(insuranceSchemeDetailPOS, po -> po.getInsuranceId() + "-" + po.getPaymentScope(), InsuranceSchemeDetailPO::getValidNum);

            otherIds.forEach(k -> {
                String welfareTypeName =  welfareTypeMap.get(Long.valueOf(k)) == 1 ? "社保" : (welfareTypeMap.get(Long.valueOf(k)) == 2 ? "公积金" : "企业年金及其它福利" );
                String welfareTypeSign =  welfareTypeMap.get(Long.valueOf(k)) == 1 ? "social" : (welfareTypeMap.get(Long.valueOf(k)) == 2 ? "fund" : "other" );
                if (insuranceIdAndScopeList.contains(k + "-" + PaymentScopeEnum.SCOPE_COMPANY.getValue())) {
                    Map<String, String> comMap = new HashMap<>();
//                    comMap.put("title", welfareTypeName + "公司" + "缴纳");
                    comMap.put("title", welfareTypeName);
                    comMap.put("titleSign", welfareTypeSign);
                    comMap.put("insuranceId", k);
                    comMap.put("insuranceName", categoryNameMap.get(Long.valueOf(k)));
                    comMap.put("paymentScope", "公司");
                    comMap.put("paymentScopeSign", "com");
                    comMap.put("validNum",schemeValidNumMap.getOrDefault(k + "-" + PaymentScopeEnum.SCOPE_COMPANY.getValue(), 2).toString());
                    resultList.add(comMap);
                }
                if (insuranceIdAndScopeList.contains(k + "-" + PaymentScopeEnum.SCOPE_PERSON.getValue())) {
                    Map<String, String> perMap = new HashMap<>();
//                    perMap.put("title", welfareTypeName + "个人" + "缴纳");
                    perMap.put("title", welfareTypeName);
                    perMap.put("titleSign", welfareTypeSign);
                    perMap.put("insuranceId", k);
                    perMap.put("insuranceName", categoryNameMap.get(Long.valueOf(k)));
                    perMap.put("paymentScope", "个人");
                    perMap.put("paymentScopeSign", "per");
                    perMap.put("validNum",schemeValidNumMap.getOrDefault(k + "-" + PaymentScopeEnum.SCOPE_PERSON.getValue(), 2).toString());
                    resultList.add(perMap);
                }
            });
        }
        return resultList;

    }

    @Override
    public void addNewBalance(BalanceAccountBaseParam param) {

        //入参判断
        if (param.getPaymentOrganization() == null || StringUtils.isBlank(param.getBillMonth()) || param.getEmployeeId() == null) {
            throw new SalaryRunTimeException(SalaryI18nUtil.getI18nLabel(0, "参数错误"));
        }

        Long employeeId = param.getEmployeeId();
        String billMonth = param.getBillMonth();
        Long creator = (long) user.getUID();
        Long paymentOrganization = param.getPaymentOrganization();

        InsuranceAccountDetailPO balanceAccountPO = getInsuranceAccountDetailMapper().getOneByBpep(InsuranceAccountDetailPO.builder()
                .billMonth(billMonth)
                .paymentStatus(PaymentStatusEnum.BALANCE.getValue())
                .employeeId(employeeId)
                .paymentOrganization(paymentOrganization)
                .build());

        if (balanceAccountPO != null) {
            throw new SalaryRunTimeException(SalaryI18nUtil.getI18nLabel(0, "补差数据已存在，不可重复新增！"));
        }
        DataCollectionEmployee employeeById = getSalaryEmployeeService(user).getEmployeeById(employeeId);

        InsuranceAccountDetailPO insuranceAccountDetailPO = new InsuranceAccountDetailPO();
        insuranceAccountDetailPO.setId(IdGenerator.generate());
        insuranceAccountDetailPO.setEmployeeId(employeeId);
        if (employeeById != null) {
            insuranceAccountDetailPO.setSubcompanyName(employeeById.getSubcompanyName());
            insuranceAccountDetailPO.setSubcompanyId(employeeById.getSubcompanyid());
            insuranceAccountDetailPO.setDepartmentName(employeeById.getDepartmentName());
            insuranceAccountDetailPO.setDepartmentId(employeeById.getDepartmentId());
            insuranceAccountDetailPO.setJobtitleName(employeeById.getJobtitleName());
            insuranceAccountDetailPO.setJobtitleId(employeeById.getJobtitleId());
            insuranceAccountDetailPO.setJobcall(employeeById.getJobcall());
            insuranceAccountDetailPO.setJobcallId(employeeById.getJobcallId());
            insuranceAccountDetailPO.setStatus(employeeById.getStatus());
        }


        insuranceAccountDetailPO.setBillMonth(billMonth);
        insuranceAccountDetailPO.setBillStatus(BillStatusEnum.NOT_ARCHIVED.getValue());
        insuranceAccountDetailPO.setPaymentStatus(PaymentStatusEnum.BALANCE.getValue());
        insuranceAccountDetailPO.setResourceFrom(ResourceFromEnum.IMPORT.getValue());

        insuranceAccountDetailPO.setCreator(creator);
        insuranceAccountDetailPO.setDeleteType(DeleteTypeEnum.NOT_DELETED.getValue());
        insuranceAccountDetailPO.setCreateTime(new Date());
        insuranceAccountDetailPO.setUpdateTime(new Date());
        insuranceAccountDetailPO.setTenantKey(SalaryDefaultTenantConstant.DEFAULT_TENANT_KEY);
        insuranceAccountDetailPO.setPaymentOrganization(paymentOrganization);
        insuranceAccountDetailPO.setSocialPayOrg(paymentOrganization);
        insuranceAccountDetailPO.setFundPayOrg(paymentOrganization);
        insuranceAccountDetailPO.setOtherPayOrg(paymentOrganization);

        InsuranceArchivesBaseInfoPO baseInfoPO = getInsuranceBaseInfoMapper().getOneByEmployeeIdAndPayOrg(employeeId, paymentOrganization);
        if (baseInfoPO != null) {
            InsuranceArchivesSocialSchemePO socialSchemePO = getSocialSchemeMapper().getOneById(baseInfoPO.getSocialArchivesId());

            InsuranceArchivesFundSchemePO fundSchemePO = getFundSchemeMapper().getOneById(baseInfoPO.getFundArchivesId());
            if (socialSchemePO != null) {
                insuranceAccountDetailPO.setSocialAccount(socialSchemePO.getSocialAccount());
            }
            if (fundSchemePO != null) {
                insuranceAccountDetailPO.setFundAccount(fundSchemePO.getFundAccount());
                insuranceAccountDetailPO.setSupplementFundAccount(fundSchemePO.getSupplementFundAccount());
            }
        }

        insuranceAccountDetailPO.setSocialPerJson(param.getSocialPerJson());
        insuranceAccountDetailPO.setSocialComJson(param.getSocialComJson());
        insuranceAccountDetailPO.setFundPerJson(param.getFundPerJson());
        insuranceAccountDetailPO.setFundComJson(param.getFundComJson());
        insuranceAccountDetailPO.setOtherPerJson(param.getOtherPerJson());
        insuranceAccountDetailPO.setOtherComJson(param.getOtherComJson());
//        insuranceAccountDetailPO.setOtherSchemeId(0L);
//        insuranceAccountDetailPO.setSocialSchemeId(0L);
//        insuranceAccountDetailPO.setFundSchemeId(0L);

        if (getSIAccountService(user).checkBalance(insuranceAccountDetailPO) && getSIAccountService(user).checkBalancePayInsurance(insuranceAccountDetailPO)) {
            accountSocialByData(insuranceAccountDetailPO, param);
            accountFundByData(insuranceAccountDetailPO, param);
            // 其他福利档案
            accountOtherByData(insuranceAccountDetailPO, param);
            account(insuranceAccountDetailPO);
            encryptUtil.encrypt(insuranceAccountDetailPO, InsuranceAccountDetailPO.class);
            getInsuranceAccountDetailMapper().batchSaveAccountDetails(Collections.singletonList(insuranceAccountDetailPO));

            //刷新bill_batch表中统计信息
            getSIAccountService(user).refreshBillBatch(paymentOrganization, billMonth);
            //记录操作日志
            encryptUtil.decrypt(insuranceAccountDetailPO, InsuranceAccountDetailPO.class);
            InsuranceAccountBatchPO targetPO = getInsuranceAccountBatchMapper().getByBillMonth(billMonth, paymentOrganization);
            TaxAgentPO taxAgentInfo = getTaxAgentMapper().getById(targetPO.getPaymentOrganization());
            LoggerContext<InsuranceAccountDetailPO> loggerContext = new LoggerContext();
            loggerContext.setUser(user);
            loggerContext.setTargetId(String.valueOf(targetPO.getId()));
            loggerContext.setTargetName(taxAgentInfo.getName() + "-" + targetPO.getBillMonth());
            loggerContext.setOperateType(OperateTypeEnum.ADD.getValue());
            loggerContext.setOperateTypeName(SalaryI18nUtil.getI18nLabel(0, "福利台账明细表-新增补差"));
            loggerContext.setOperatedesc(SalaryI18nUtil.getI18nLabel(0, "福利台账明细表-新增补差")
                    + ":" + taxAgentInfo.getName() + "-" + targetPO.getBillMonth());
            loggerContext.setNewValues(insuranceAccountDetailPO);
            SalaryElogConfig.siAccountLoggerTemplate.write(loggerContext);
        } else {
            throw new SalaryRunTimeException(SalaryI18nUtil.getI18nLabel(0,  "补差数据中存在福利档案中未设置的福利项缴纳数值，请检查补差缴纳信息！"));
        }

    }

    public List<String> payInsuranceIdAndScopeList(Long socialSchemeId) {
        //查询该福利方案下开启缴纳的福利项
        List<InsuranceSchemeDetailPO> detailPOS = getInsuranceSchemeDetailMapper().queryListBySchemeId(socialSchemeId);
        List<String> insuranceIdList = new ArrayList<>();
        if (detailPOS != null && detailPOS.size() > 0) {
            //开启缴纳的
            insuranceIdList = detailPOS.stream().filter(f -> f.getIsPayment().equals(IsPaymentEnum.YES.getValue())).map(m -> {
                return m.getInsuranceId() .toString() + "-" + m.getPaymentScope().toString();
            }).collect(Collectors.toList());
        }
        return insuranceIdList;
    }

    public InsuranceAccountDetailPO account(InsuranceAccountDetailPO insuranceAccountDetailPO) {
        //个人合计
        BigDecimal socialPerson =
                StringUtils.isBlank(insuranceAccountDetailPO.getSocialPerSum()) ? new BigDecimal("0") : new BigDecimal(insuranceAccountDetailPO.getSocialPerSum());
        BigDecimal fundPerson =
                StringUtils.isBlank(insuranceAccountDetailPO.getFundPerSum()) ? new BigDecimal("0") : new BigDecimal(insuranceAccountDetailPO.getFundPerSum());
        BigDecimal otherPerson =
                StringUtils.isBlank(insuranceAccountDetailPO.getOtherPerSum()) ? new BigDecimal("0") : new BigDecimal(insuranceAccountDetailPO.getOtherPerSum());
        BigDecimal perSum = socialPerson.add(fundPerson).add(otherPerson);
        insuranceAccountDetailPO.setPerSum(perSum.toPlainString());
        //单位合计
        BigDecimal socialCom =
                StringUtils.isBlank(insuranceAccountDetailPO.getSocialComSum()) ? new BigDecimal("0") : new BigDecimal(insuranceAccountDetailPO.getSocialComSum());
        BigDecimal fundCom = StringUtils.isBlank(insuranceAccountDetailPO.getFundComSum()) ? new BigDecimal("0") : new BigDecimal(insuranceAccountDetailPO.getFundComSum());
        BigDecimal otherCom =
                StringUtils.isBlank(insuranceAccountDetailPO.getOtherComSum()) ? new BigDecimal("0") : new BigDecimal(insuranceAccountDetailPO.getOtherComSum());
        BigDecimal comSum = socialCom.add(fundCom).add(otherCom);
        insuranceAccountDetailPO.setComSum(comSum.toPlainString());
        //社保合计
        insuranceAccountDetailPO.setSocialSum(socialPerson.add(socialCom).toPlainString());
        //公积金合计
        insuranceAccountDetailPO.setFundSum(fundPerson.add(fundCom).toPlainString());
        //其他福利合计
        insuranceAccountDetailPO.setOtherSum(otherPerson.add(otherCom).toPlainString());
        //合计
        insuranceAccountDetailPO.setTotal(perSum.add(comSum).toPlainString());
        return insuranceAccountDetailPO;
    }

    public void accountFundByData(InsuranceAccountDetailPO insuranceAccountDetailPO, BalanceAccountBaseParam baseParam) {
        //公积金个人
        if (StringUtils.isNotBlank(baseParam.getFundPerJson())) {
            List<BigDecimal> fundPer = new ArrayList<>();
            HashMap<String, String> fundPerson = JSON.parseObject(baseParam.getFundPerJson(), new HashMap<String, String>().getClass());
            fundPerson.forEach((k, v) -> {
                BigDecimal result = new BigDecimal(v);
                fundPer.add(result);
            });
            insuranceAccountDetailPO.setFundPerJson(baseParam.getFundPerJson());
            BigDecimal fundPerSum = new BigDecimal("0");
            for (BigDecimal bigDecimal : fundPer) {
                fundPerSum = fundPerSum.add(bigDecimal);
            }
            insuranceAccountDetailPO.setFundPerSum(fundPerSum.toPlainString());
        }
        //公积金单位
        if (StringUtils.isNotBlank(baseParam.getFundComJson())) {
            List<BigDecimal> fundCom = new ArrayList<>();
            HashMap<String, String> fundComMap = JSON.parseObject(baseParam.getFundComJson(), new HashMap<String, String>().getClass());
            fundComMap.forEach((k, v) -> {
                BigDecimal result = new BigDecimal(v);
                fundCom.add(result);
            });
            insuranceAccountDetailPO.setFundComJson(baseParam.getFundComJson());
            BigDecimal fundComSum = new BigDecimal("0");
            for (BigDecimal bigDecimal : fundCom) {
                fundComSum = fundComSum.add(bigDecimal);
            }
            insuranceAccountDetailPO.setFundComSum(fundComSum.toPlainString());
        }
    }

    public void accountOtherByData(InsuranceAccountDetailPO insuranceAccountDetailPO, BalanceAccountBaseParam baseParam) {
        //其他福利个人
        if (StringUtils.isNotBlank(baseParam.getOtherPerJson())) {
            List<BigDecimal> otherPer = new ArrayList<>();
            HashMap<String, String> otherPerMap = JSON.parseObject(baseParam.getOtherPerJson(), new HashMap<String, String>().getClass());
            otherPerMap.forEach((k, v) -> {
                BigDecimal result = new BigDecimal(v);
                otherPer.add(result);
            });
            insuranceAccountDetailPO.setOtherPerJson(baseParam.getOtherPerJson());
            BigDecimal otherPerSum = new BigDecimal("0");
            for (BigDecimal bigDecimal : otherPer) {
                otherPerSum = otherPerSum.add(bigDecimal);
            }
            insuranceAccountDetailPO.setOtherPerSum(otherPerSum.toPlainString());
        }
        //其他福利单位
        if (StringUtils.isNotBlank(baseParam.getOtherComJson())) {
            List<BigDecimal> otherCom = new ArrayList<>();
            HashMap<String, String> otherComMap = JSON.parseObject(baseParam.getOtherComJson(), new HashMap<String, String>().getClass());
            otherComMap.forEach((k, v) -> {
                BigDecimal result = new BigDecimal(v);
                otherCom.add(result);
            });
            insuranceAccountDetailPO.setOtherComJson(baseParam.getOtherComJson());
            BigDecimal otherComSum = new BigDecimal("0");
            for (BigDecimal bigDecimal : otherCom) {
                otherComSum = otherComSum.add(bigDecimal);
            }
            insuranceAccountDetailPO.setOtherComSum(otherComSum.toPlainString());
        }
    }

    public void accountSocialByData(InsuranceAccountDetailPO insuranceAccountDetailPO, BalanceAccountBaseParam baseParam) {
        //社保个人
        if (StringUtils.isNotBlank(baseParam.getSocialPerJson())) {
            List<BigDecimal> socialPer = new ArrayList<>();
            HashMap<String, String> archivesPerson = JSON.parseObject(baseParam.getSocialPerJson(), new HashMap<String, String>().getClass());
            archivesPerson.forEach((k, v) -> {
                BigDecimal result = new BigDecimal(v);
                socialPer.add(result);
            });
            insuranceAccountDetailPO.setSocialPerJson(baseParam.getSocialPerJson());
            BigDecimal socialPerSum = new BigDecimal("0");
            for (BigDecimal bigDecimal : socialPer) {
                socialPerSum = socialPerSum.add(bigDecimal);
            }
            insuranceAccountDetailPO.setSocialPerSum(socialPerSum.toPlainString());
        }
        //社保单位
        if (StringUtils.isNotBlank(baseParam.getSocialComJson())) {
            List<BigDecimal> socialCom = new ArrayList<>();
            HashMap<String, String> archivesCom = JSON.parseObject(baseParam.getSocialComJson(), new HashMap<String, String>().getClass());
            archivesCom.forEach((k, v) -> {
                BigDecimal result = new BigDecimal(v);
                socialCom.add(result);
            });
            insuranceAccountDetailPO.setSocialComJson(baseParam.getSocialComJson());
            BigDecimal socialComSum = new BigDecimal("0");
            for (BigDecimal bigDecimal : socialCom) {
                socialComSum = socialComSum.add(bigDecimal);
            }
            insuranceAccountDetailPO.setSocialComSum(socialComSum.toPlainString());
        }
    }



}
